package com.smart.translator.data;

import android.content.Context;
import android.util.Log;
import com.smart.translator.util.ConfigManager;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;

/**
 * 统计API服务类
 */
public class StatsApiService {
    private static final String TAG = "StatsApiService";
    private static final String TTS_STATS_ENDPOINT = "/api/stats/tts";
    private static final String ASR_STATS_ENDPOINT = "/api/stats/asr";

    /**
     * 获取服务器地址
     */
    private static String getServerUrl(Context context) {
        try {
            android.content.SharedPreferences prefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e(TAG, "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
    
    /**
     * 构建完整的API URL
     */
    private static String buildApiUrl(Context context, String path) {
        String serverUrl = getServerUrl(context);
        return "http://" + serverUrl + /*"/v1" +*/ path;
    }

    /**
     * 上传TTS统计数据
     */
    public static CompletableFuture<ApiResponse<String>> uploadStats(Context context, int userId, int textLength) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                String statsUrl = buildApiUrl(context, TTS_STATS_ENDPOINT);
                Log.d(TAG, "statsUrl " + statsUrl);
                // 获取当前日期
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String currentDate = dateFormat.format(new Date());
                
                // 构建请求JSON
                JSONObject requestJson = new JSONObject();
                requestJson.put("user_id", userId);
                requestJson.put("text_length", textLength);
                requestJson.put("date", currentDate);

                Log.d(TAG, "准备上传统计数据: " + requestJson.toString());

                // 发送请求
                HttpURLConnection connection = (HttpURLConnection) new URL(statsUrl).openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);

                // 发送请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 读取响应
                int responseCode = connection.getResponseCode();
                StringBuilder response = new StringBuilder();
                
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                }

                Log.d(TAG, "统计响应: " + response.toString());

                if (responseCode == 200) {
                    // 上传成功
                    return ApiResponse.success("统计数据上传成功");
                } else {
                    // 上传失败
                    JSONObject errorResponse = new JSONObject(response.toString());
                    String errorMessage = errorResponse.optString("detail", "统计数据上传失败");
                    return ApiResponse.error(errorMessage);
                }

            } catch (Exception e) {
                Log.e(TAG, "统计数据上传失败", e);
                return ApiResponse.error("网络请求失败: " + e.getMessage());
            }
        });
    }

    /**
     * 上传ASR统计数据
     */
    public static CompletableFuture<ApiResponse<String>> uploadAsrStats(Context context, int userId, int seconds) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                String statsUrl = buildApiUrl(context, ASR_STATS_ENDPOINT);
                Log.d(TAG, "ASR statsUrl " + statsUrl);
                // 获取当前日期
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                String currentDate = dateFormat.format(new Date());
                
                // 构建请求JSON
                JSONObject requestJson = new JSONObject();
                requestJson.put("user_id", userId);
                requestJson.put("seconds", seconds);
                requestJson.put("date", currentDate);

                Log.d(TAG, "准备上传ASR统计数据: " + requestJson.toString());

                // 发送请求
                HttpURLConnection connection = (HttpURLConnection) new URL(statsUrl).openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/json");
                connection.setDoOutput(true);

                // 发送请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestJson.toString().getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                // 读取响应
                int responseCode = connection.getResponseCode();
                StringBuilder response = new StringBuilder();
                
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        response.append(line);
                    }
                }

                Log.d(TAG, "ASR统计响应: " + response.toString());

                if (responseCode == 200) {
                    // 上传成功
                    return ApiResponse.success("ASR统计数据上传成功");
                } else {
                    // 上传失败
                    JSONObject errorResponse = new JSONObject(response.toString());
                    String errorMessage = errorResponse.optString("detail", "ASR统计数据上传失败");
                    return ApiResponse.error(errorMessage);
                }

            } catch (Exception e) {
                Log.e(TAG, "ASR统计数据上传失败", e);
                return ApiResponse.error("网络请求失败: " + e.getMessage());
            }
        });
    }
} 